package com.jiazhong.basic.shuxin.thread.a;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

public class App {

    private static void a() {
        DemoA a = new DemoA();
        Thread t1 = new Thread(a::a);
        Thread t2 = new Thread(a::a);
        t1.start();
        t2.start();
    }

    @SneakyThrows
    private static void b1() {
        DemoB b = new DemoB();
        Thread t1 = new Thread(b::b1);
        Thread t2 = new Thread(b::b1);
        t1.start();
        t2.start();
        Thread.sleep(5000);
        Thread t3 = new Thread(b::b2);
        t3.start();
    }

    @SneakyThrows
    private static void b2() {
        DemoB b = new DemoB();
        Thread t1 = new Thread(b::b3);
        Thread t2 = new Thread(b::b3);
        t1.start();
        t2.start();
    }

    private static void c() {
        DemoC c = new DemoC();
        Thread t1 = new Thread(c::c);
        Thread t2 = new Thread(c::c);
        Thread t3 = new Thread(c::c);
        t1.start();
        t2.start();
        t3.start();
    }

    @SneakyThrows
    private static void d() {
        DemoD d = new DemoD();
        Thread t = new Thread(d::jisuan);
        t.start();
        // 让主线程等待t线程执行完毕后开始执行
        // t.join();
        t.join(2100);
        System.out.println("开始执行获取结果操作");
        // 还没有计算完毕 开始输出内容
        int sum = d.sum();
        System.out.println(sum);
    }
    @SneakyThrows
    private static void e() {
        Object lock1 = new Object();
        Object lock2 = new Object();
        Thread t1 = new Thread(()->{
            synchronized (lock1){
                System.out.println("A获取到了锁A");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (lock2){
                    System.out.println("A获取到了锁B");
                }
            }


        });
        t1.start();
        Thread t2 = new Thread(()->{
            synchronized (lock1){
                System.out.println("B获取到了锁A");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (lock2){
                    System.out.println("B获取到了锁B");
                }
            }

        });
        t2.start();
    }

    public static void main(String[] args) {
        e();
    }
}
